package com.anolesoft.amljmes.billing.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.anolesoft.amljmes.billing.dto.GdyjDykhxDto;
import com.anolesoft.amljmes.billing.dto.GdyjDykhxInport;
import com.anolesoft.amljmes.billing.service.GdyjDykhxService;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.twelvePlan.entity.MesEqualCatalogDO;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class GdyjDykhxListener implements ReadListener<GdyjDykhxInport> {
    private static final int BATCH_COUNT = 1000;

    private List<GdyjDykhxInport> list = new ArrayList<>();

    private List<GdyjDykhxDto> communityList = new ArrayList<>(BATCH_COUNT);

    private GdyjDykhxService gdyjDykhxService;

    public GdyjDykhxListener(GdyjDykhxService gdyjDykhxService){
        this.gdyjDykhxService = gdyjDykhxService;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {

    }

    @Override
    public void invoke(GdyjDykhxInport data, AnalysisContext context) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        GdyjDykhxDto gdyjDykhxDto = BeanUtil.copyProperties(data, GdyjDykhxDto.class);
        gdyjDykhxDto.setCjr(loginUser.getEmpUid());
        gdyjDykhxDto.setFactoryId(loginUser.getFacCode());


        communityList.add(gdyjDykhxDto);
        if (communityList.size() >= BATCH_COUNT) {
            batchInsert();
            // 存储完成清理 list
            communityList.clear();
        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        batchInsert();
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return true;
    }

    void batchInsert(){
        log.debug("数据：{}", communityList);
        gdyjDykhxService.uploadExcel(communityList);
    }
}
